<?php

namespace App\Modules\LuckDraw\Exp;

use App\Modules\LuckDraw\Lib\StrLib;
use Illuminate\Support\Facades\Redis;

class EnergyExp implements ExpInterface {
    private $_id;
    private $_name;
    private $_enName;
    private $_redisKeyUserExpNum = 'LUCKDRAW:CACHE:USER:EXP:%d:%s';

    public function __construct(int $id, string $name, string $enName){
        $this->_id = $id;
        $this->_name = $name;
        $this->_enName = $enName;
    }
    public function getId(): ?int  {
        // TODO: Implement getId() method.
        return $this->_id;
    }

    public function getName(): ?string {
        // TODO: Implement getName() method.
        return $this->_name;
    }

    public function getEnName(): ?string {
        // TODO: Implement getEnName() method.
        return $this->_enName;
    }

    public function getExpNum(?int $userId = null, ?int $roomId=null): int {
        // TODO: Implement getExpNum() method.
        $week = date('Y-m-d', strtotime('this week'));
        $key = sprintf($this->_redisKeyUserExpNum, $this->getId(), $week);
        return intval(Redis::HGET($key, $userId)??0);
    }

    public function addExpNum(int $num = 0, ?int $userId=null, ?int $roomId=null): bool {
        // TODO: Implement addExpNum() method.
        $week = date('Y-m-d', strtotime('this week'));
        $key = sprintf($this->_redisKeyUserExpNum,$this->getId(), $week);
        if (Redis::EXISTS($this->_redisKeyUserExpNum)) {
            $incNum = Redis::HINCRBY($key, $userId, $num);
        } else {
            $incNum = Redis::HINCRBY($key, $userId, $num);
            Redis::EXPIRE($key, 7 * 3600 * 24 + 3600);
        }

        return $incNum > 0;
    }

    public function enough(?int $need = null, ?int $userId = null, ?int $roomId = null): bool {
        if ($need == null || $need <= 0) {
            return true;
        }
        if ($userId == null) {
            return false;
        }
        return $this->getExpNum($userId) >= $need;
    }
}